package cn.wowjoy.commonlibrary.base;


import cn.wowjoy.commonlibrary.bean.BaseResponse;
import cn.wowjoy.commonlibrary.bean.baseLiveData.LiveDataWrapper;
import cn.wowjoy.commonlibrary.utils.DebugUtil;
import cn.wowjoy.commonlibrary.widget.statelayout.StateLayout;
import io.reactivex.functions.Consumer;

/**
 *
 */

public abstract class BaseConsumer<T extends BaseResponse> implements Consumer<LiveDataWrapper<T>> {


    protected StateLayout mStateLayout;

    public void setStateLayout(StateLayout mStateLayout) {
        this.mStateLayout = mStateLayout;
    }

    public BaseConsumer() {
    }

    public BaseConsumer(StateLayout mStateLayout) {
        this.mStateLayout = mStateLayout;
    }

    @Override
    public void accept(LiveDataWrapper<T> tLiveDataWrapper) throws Exception {
        switch (tLiveDataWrapper.status) {
            case LOADING:
                DebugUtil.debug("BaseObserver", "加载中");
                if (null != mStateLayout) {
                    mStateLayout.showLoadingView();
                }
                onStart();
                break;
            case ERROR:
                DebugUtil.debug("BaseObserver", "失败");
                if (null != mStateLayout) {
                    mStateLayout.showErrorView();
                }
                onError(tLiveDataWrapper.error);
                break;
            case SUCCESS:
                DebugUtil.debug("BaseObserver", "成功");
                if (null != tLiveDataWrapper.data && null != tLiveDataWrapper.data.getData()) {
                    if (null != mStateLayout) {
                        mStateLayout.showContentView();
                    }
                } else {
                    if (null != mStateLayout) {
                        mStateLayout.showEmptyView();
                    }
                }
                onSuccess(tLiveDataWrapper.data);
                break;
            default:
                break;
        }
    }

    protected void onStart() {}

    protected void onError(Throwable error){}

    protected abstract void onSuccess(T data);

}
